package com.student.controller;

import com.student.model.Course;
import com.student.model.CourseDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseDAO courseDAO;

    @PostMapping("/add")    //添加课程
    public ResponseEntity<?> add(@RequestBody Course course){
        if(courseDAO.existsByCourseName(course.getCourseName())){
            return new ResponseEntity<>("该课程已存在", HttpStatus.BAD_REQUEST);
        }else{
            return new ResponseEntity<Course>(courseDAO.save(course),HttpStatus.OK);
        }
    }


    @DeleteMapping("/delete")    //删除课程
    public ResponseEntity<?> delete(String courseName){
        if(!courseDAO.existsByCourseName(courseName)){
            return new ResponseEntity<>("该课程不存在",HttpStatus.BAD_REQUEST);
        }else{
            courseDAO.deleteByCourseName(courseName);
            return new ResponseEntity<>("删除成功",HttpStatus.OK);
        }
    }

    @GetMapping("/findOne")        //根据课程名查一堂课
    public ResponseEntity<?> findOne(String courseName){
        if(courseDAO.existsByCourseName(courseName))
            return new ResponseEntity<>(courseDAO.findCourseByCourseName(courseName),HttpStatus.OK);
        return new ResponseEntity<>("该课程不存在",HttpStatus.BAD_REQUEST);
    }

    @GetMapping("/findAll")      //查出（显示）所有课程信息
    public ResponseEntity<List<Course>> findAll(){
        return new ResponseEntity<>(courseDAO.findAll(),HttpStatus.OK) ;
    }





}
